﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;

namespace NetSync.Core
{
    public interface INetSerialize : IDisposable
    {
        Task<byte[]> SerializeAsync<T>(T data);

        Task<T> DeSerializeAsync<T>(byte[] data);
    }

    public class NewtonsoftJsonNetSerialize : INetSerialize
    {
        private readonly JsonSerializer _jsonSerializer;

        public NewtonsoftJsonNetSerialize(JsonSerializerSettings settins = null)
        {
            _jsonSerializer = JsonSerializer.Create(settins);
        }

        public async Task<T> DeSerializeAsync<T>(byte[] data)
        {
            if (data == null || data.Length == 0) return default(T);
            _jsonSerializer.CheckAdditionalContent = true;
            using (var ms = new MemoryStream(data))
            {
                using (var sr = new StreamReader(ms))
                {
                    using (var reader = new JsonTextReader(sr))
                    {
                        var result = _jsonSerializer.Deserialize<T>(reader);
                        return await Task.FromResult(result);
                    }
                }
            }
        }

        public Task<byte[]> SerializeAsync<T>(T data)
        {
            _jsonSerializer.CheckAdditionalContent = true;
            using (var ms = new MemoryStream())
            {
                using(var sw = new StreamWriter(ms))
                {
                    using(var writer = new JsonTextWriter(sw))
                    {
                        _jsonSerializer.Serialize(writer, data, typeof(T));
                        writer.Flush();
                        return Task.FromResult(ms.ToArray());
                    }
                }
            }
        }

        public void Dispose()
        {

        }
    }
}